package com.apex.spark.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 表结构解析方法
 */
public class SchemaUtil {
    public static StructType getTypeInformation(JSONObject json) {
        int size = json.size();
//        String[] fields = new String[size];
        List<StructField> informations = new LinkedList<>();
        int i = 0;
        for (Map.Entry<String, Object> entry : json.entrySet()) {
//            String key = entry.getKey();
            Object value = entry.getValue();
//            fields[i] = key;
            if (value instanceof String) {
                informations.add(DataTypes.createStructField(entry.getKey(), DataTypes.StringType, true));
            } else if (value instanceof Integer) {
                informations.add(DataTypes.createStructField(entry.getKey(), DataTypes.IntegerType, true));
            } else if (value instanceof Long) {
                informations.add(DataTypes.createStructField(entry.getKey(), DataTypes.LongType, true));
            } else if (value instanceof BigDecimal) {
                informations.add(DataTypes.createStructField(entry.getKey(), DataTypes.createDecimalType(), true));
            }
            i++;
        }
        return DataTypes.createStructType(informations);
    }
}
